package com.block.source.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.InfoTypeEnum;
import com.block.common.exception.NotifyExceptionService;
import com.block.common.model.vo.ResultInfoVO;
import com.block.common.service.ISourceBaseInfoService;
import com.block.common.service.LogFactory;
import com.block.db.entity.*;
import com.block.merchant.service.IMerchantBaseInfoService;
import com.block.source.enums.ReceiveTypeEnum;
import com.block.source.factory.SourceApiFactory;
import com.block.source.model.dto.SourceApiParam;
import com.block.source.model.dto.SourceApiResult;
import com.block.source.model.param.UserDataParam;
import com.block.source.service.*;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class SourceApiRegisterUserService implements ISourceApiRegisterUserService {

    private static final Logger log = LogFactory.getSourceLog();

    @Autowired
    NotifyExceptionService notifyExceptionService;
    @Autowired
    ISourceBaseInfoService sourceBaseInfoService;
    @Autowired
    ISourceRegisterUserService sourceRegisterUserService;
    @Autowired
    IMerchantBaseInfoService merchantBaseInfoService;
    @Autowired
    ISourcePushResultInfoService sourcePushResultInfoService;


    @Override
    public JSONObject apiRegisterUser(String channelCode, Map<String, String[]> parameterMap, String paramContent, String requestIp){

        String message = StrUtil.format("【线索api进件】请求数据展示【channelCode】{}【parameterMap】{}【paramContent】{}", channelCode, JSON.toJSONString(parameterMap), paramContent);
        log.info(message);

        try {

            // 查询基本信息
            SourceBaseInfo sourceBaseInfo = sourceBaseInfoService.getSourceBaseInfoByCode(channelCode);
            if (ObjectUtil.isEmpty(sourceBaseInfo)){
                JSONObject error = SourceApiFactory.getService(ReceiveTypeEnum.DEFAULT.getValue()).getError("渠道信息为空");
                return error;
            }

            ISourceReceiveService sourceReceiveService = SourceApiFactory.getService(sourceBaseInfo.getFactoryType());
            if (!ObjectUtil.equals(sourceBaseInfo.getStatus(), Integer.valueOf(1))){
                JSONObject error = sourceReceiveService.getError("渠道信息不可用");
                return error;
            }
            if (!ObjectUtil.equals(sourceBaseInfo.getType(), InfoTypeEnum.APIS.getValue())){
                JSONObject error = sourceReceiveService.getError("渠道类型错误，非双授权");
                return error;
            }

            // 基本信息判断
            // 根据请求信息，构造需要的参数信息
            SourceApiResult sourceApiResult = sourceReceiveService.handleRegisterUserData(sourceBaseInfo, parameterMap, paramContent);
            log.info("【线索api进件】进件数据转换完毕【channelCode】{}【sourceApiResult】{}", sourceBaseInfo.getChannelCode(), JSON.toJSONString(sourceApiResult));
            if (!sourceApiResult.isSuccess()){
                return sourceApiResult.getReturnObject();
            }

            UserDataParam userDataParam = sourceApiResult.getUserDataParam();
            userDataParam.setRequestIp(requestIp);

            // 进行数据进件
            ResultInfoVO resultInfoVO = sourceRegisterUserService.sourceRegisterUser1(userDataParam.getOrderNo(), sourceBaseInfo, userDataParam);

            log.info("【线索api进件】数据进件完成【channelCode】{}【resultInfoVO】{}", channelCode, JSON.toJSONString(resultInfoVO));
            if (!resultInfoVO.isSuccess()){
                return sourceReceiveService.getError(resultInfoVO.getRespMsg());
            }

            // 根据返回结果，构造渠道方需要的数据
            JSONObject data = resultInfoVO.getData();

            MerchantThirdBaseInfo thirdBaseInfo = data.getObject("thirdBaseInfo", MerchantThirdBaseInfo.class);
            List<MerchantThirdProtocolInfo> thirdProtocolInfoList = data.getObject("thirdProtocolInfoList", List.class);

            // 根据请求信息，构造需要的参数信息
            SourceApiParam sourceApiParam = new SourceApiParam();
            sourceApiParam.setExtObject(sourceApiResult.getExtObject());
            SourcePushResultInfo sourcePushResultInfo = sourcePushResultInfoService.getById(userDataParam.getOrderNo());

            MerchantBaseInfo merchantBaseInfo = merchantBaseInfoService.getById(sourcePushResultInfo.getInfoId());
            sourceApiParam.setMerchantBaseInfo(merchantBaseInfo);
            sourceApiParam.setSourcePushResultInfo(sourcePushResultInfo);

            sourceApiParam.setThirdBaseInfo(thirdBaseInfo);
            sourceApiParam.setThirdProtocolInfoList(thirdProtocolInfoList);

            SourceApiResult checkUserResult = sourceReceiveService.getRegisterUserReturnData(sourceBaseInfo, resultInfoVO,sourceApiParam);
            // 返回数据
            log.info("【线索api进件】请求完成，返回进件数据【channelCode】{}【checkUserResult】{}", channelCode, JSON.toJSONString(checkUserResult));
            return checkUserResult.getReturnObject();
        }catch (Exception exception){
            exception.printStackTrace();
            notifyExceptionService.notifyNoticeInfo("SOURCE_API_REGSTER_EXEC", "线索api进件异常", message, exception);
        }
        return SourceApiFactory.getService(ReceiveTypeEnum.DEFAULT.getValue()).getError("进件异常");
    }

    @Override
    public JSONObject callback1(String channelCode, Map<String, String[]> parameterMap, String paramContent) {

        String message = StrUtil.format("【线索callBack】请求数据展示【channelCode】{}【parameterMap】{}【paramContent】{}", channelCode, JSON.toJSONString(parameterMap), paramContent);
        log.info(message);

        try {

            // 查询基本信息
            SourceBaseInfo sourceBaseInfo = sourceBaseInfoService.getSourceBaseInfoByCode(channelCode);
            if (ObjectUtil.isEmpty(sourceBaseInfo)){
                JSONObject error = SourceApiFactory.getService(ReceiveTypeEnum.DEFAULT.getValue()).getError("渠道信息为空");
                return error;
            }

            ISourceCallBackService callBackService = SourceApiFactory.getCallBackService(sourceBaseInfo.getFactoryType());
            if (!ObjectUtil.equals(sourceBaseInfo.getStatus(), Integer.valueOf(1))){
                return SourceApiFactory.getService(ReceiveTypeEnum.DEFAULT.getValue()).getError("申请异常");
            }

            // 基本信息判断
            // 根据请求信息，构造需要的参数信息
            SourceApiResult sourceApiResult = callBackService.getCallBack1Data(sourceBaseInfo, parameterMap, paramContent);
            log.info("【线索api申请回调】进件数据转换完毕【channelCode】{}【sourceApiResult】{}", channelCode, JSON.toJSONString(sourceApiResult));

            return sourceApiResult.getCallBack1Data();
        }catch (Exception exception){
            exception.printStackTrace();
            notifyExceptionService.notifyNoticeInfo("SOURCE_API_REGSTER_EXEC", "线索api申请异常", message, exception);
        }
        return SourceApiFactory.getService(ReceiveTypeEnum.DEFAULT.getValue()).getError("申请异常");
    }

}
